#include <gio/gio.h>
#include <iostream>

// 检查指定键是否存在且类型正确
bool is_key_valid(GSettings* settings, const gchar* key, const gchar* expected_type) {
    if (!settings || !key || !expected_type) {
        return false;
    }

    gchar** keys = g_settings_list_keys(settings);
    if (!keys) {
        return false;
    }

    // 检查键是否存在  通过g_settings_get_value接口直接获取不存在的键会越界
    bool key_exists = false;
    for (gchar** k = keys; *k; k++) {
        if (g_strcmp0(*k, key) == 0) {
            key_exists = true;
            break;
        }
    }
    g_strfreev(keys);

    if (!key_exists) {
        std::cerr << "Key '" << key << "' does not exist in schema." << std::endl;
        return false;
    }

    // 检查键类型是否匹配
    GVariantType* expected_var_type = g_variant_type_new(expected_type);
    GVariant* value = g_settings_get_value(settings, key);
    const GVariantType* actual_var_type = g_variant_get_type(value);//返回是引用不需要释放
    
    bool type_matches = g_variant_type_equal(expected_var_type, actual_var_type);
    
    g_variant_unref(value);
    g_variant_type_free(expected_var_type);

    if (!type_matches) {
        return false;
    }

    return true;
}


// 回调函数，当设置值变化时被调用
void on_ai_index_enable_changed(GSettings* settings, 
                               const gchar* key, 
                               gpointer user_data) {
    
    gboolean value = g_settings_get_boolean(settings, key);
    std::cout <<"kye"<<key <<" "<< value<< std::endl;
    // std::cout << "ai-index-enable changed to: " << (value ? "true" : "false") << std::endl;
}

int main() {
    const gchar* schema_id = "org.ukui.search.settings";
    const gchar* key_name = "ai-index-enable";
    const gchar* expected_type = "b";  // 'b' 表示布尔类型

    // 创建 GSettings 对象
    GSettings* settings = g_settings_new("org.ukui.search.settings");
    
    if (!settings) {
        std::cerr << "Failed to create GSettings object" << std::endl;
        return 1;
    }
    
    // 验证键是否存在且类型正确
    if (!is_key_valid(settings, key_name, expected_type)) {
        g_object_unref(settings);
        return 1;
    }

    // 连接信号，监控值变化  // 注意要判断是否有key，要不就越界了
    g_signal_connect(settings, "changed::ai-index-enable", 
                    G_CALLBACK(on_ai_index_enable_changed), NULL);

    // 获取当前值
    gboolean current_value = g_settings_get_boolean(settings, "ai-index-enable");
    
    std::cout << "Current ai-index-enable value: " << (current_value ? "true" : "false") << std::endl;

    // 进入主循环以保持程序运行并接收信号
    GMainLoop* loop = g_main_loop_new(NULL, FALSE);
    g_main_loop_run(loop);

    // 清理资源
    g_object_unref(settings);
    g_main_loop_unref(loop);

    return 0;
}